﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using Newtonsoft.Json;
using Fly.Common.Linq;
using RN.ERP.Web.ModelService;
using RN.ERP.Web.EnterpriseService;
using RN.ERP.Web.BasicService;

namespace RN.ERP.Web.CA
{
    public partial class CAManagerRegAudit : BasePage
    {
        EnterpriseServiceClient enterpriseClient = new EnterpriseServiceClient();
        BasicServiceClient basicServiceClient = new BasicServiceClient();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindFlowCode();
            }
        }

        protected void ListCorps_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
        {
            var queryCondition = hdnCondition.Value;
            if (string.IsNullOrEmpty(queryCondition))
            {
                queryCondition = GetCondition();
            }
            int pageSize = ListCorps.PageSize;
            int pageIndex = ListCorps.CurrentPageIndex + 1;
            int count = 0;
            var corps = enterpriseClient.GetManagerRegListYT(out count, pageIndex, pageSize, queryCondition, "06");
            var listNews = JsonConvert.DeserializeObject<IList<CompanyInfo>>(corps).ToList();
            int cnt = count;
            ListCorps.VirtualItemCount = cnt;
            ListCorps.DataSource = listNews;
        }

        //获取查询条件
        private string GetCondition()
        {
            List<string> listFlow = GetFlowCodes();
            List<QueryCompanyInfoCondition> queryList = new List<QueryCompanyInfoCondition>();
            foreach (var f in listFlow)
            {
                QueryCompanyInfoCondition condition = new QueryCompanyInfoCondition();
                string title = txtTitle.Text.Trim();
                if (!string.IsNullOrEmpty(title))
                {
                    condition.Introduction = new ParameterValue<string>() { O = OptEnum.Like, V = title };
                }

                if (!string.IsNullOrEmpty(f))
                {
                    condition.FlowCode = new ParameterValue<string>() { O = OptEnum.Equal, V = f };
                }
                queryList.Add(condition);
            }
            return JsonConvert.SerializeObject(queryList);


          
        }

        private string AuditCorpReg(string data, string opt, string flowcode, string content)
        {
            string currentAreaCode = UserInfo.CurrentArea;
            User_Log log = new User_Log();
            log.IsrtDate = DateTime.Now;
            log.IsrtUser = UserInfo.CorpUserGuid;
            log.IsrtUserName = UserInfo.Name;
            log.IsrtUserArea = currentAreaCode;
            log.IsrtUserRole = UserInfo.RoleId;
            log.FunctionId = opt;
            log.Content = content;
            log.Notice = hdnComments.Value;
            var result = enterpriseClient.ManagerRegAudit(data, currentAreaCode, JsonConvert.SerializeObject(log), flowcode, "", false);
            return result;
        }

        private List<string> GetFlowCodes()
        {
            string flowCode = ddlStatus.SelectedValue;
            List<string> listFlow = new List<string>();
            foreach (var f in flowCode.Split('|'))
            {
                if (f!=null)
                {
                    listFlow.Add(f);
                }
            }
            return listFlow;
        }

        private void BindFlowCode()
        {
            string msg = string.Empty;
            var dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(basicServiceClient.GetAllFlowStatus(out msg, UserInfo.CurrentArea, UserInfo.RoleId, "10006"));
            ddlStatus.Items.Clear();
            foreach (var key in dic.Keys)
            {
                ddlStatus.Items.Add(new ListItem(key, dic[key]));
            }
            ddlStatus.Items.Insert(0, new ListItem("全部", ""));
            if (dic.ContainsKey("处理中"))
            {
                ddlStatus.Items.FindByText("处理中").Selected = true;
            }
        }

        /// <summary>
        /// 客户端grid刷新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void RadAjaxManager1_AjaxRequest(object sender, AjaxRequestEventArgs e)
        {
            switch (e.Argument)
            {
                #region Rebind
                case "Rebind":
                    
                    ListCorps.MasterTableView.SortExpressions.Clear();
                    ListCorps.MasterTableView.GroupByExpressions.Clear();
                    ListCorps.Rebind();
                    break;
                #endregion

                #region Audit
                case "Audit":
                    try
                    {
                        int checkCount = 0;
                        string flowcode = string.Empty;
                        string strGuid = string.Empty;
                        string comments = hdnComments.Value;
                        foreach (GridDataItem dataItem in ListCorps.MasterTableView.Items)
                        {
                            if ((dataItem.FindControl("CheckBox1") as CheckBox).Checked == true)
                            {
                                strGuid = dataItem.GetDataKeyValue("CorpUserGuid").ToString();
                                flowcode = dataItem["FlowCode"].Text;
                                checkCount++;
                                if (checkCount >= 2)
                                {
                                    //只能选择一条数据
                                    ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('只能选择一条数据！');", true);
                                    return;
                                }
                            }
                        }
                        if (checkCount == 0)
                        {
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('请选择要审核的数据！');", true);
                        }
                        else if (checkCount == 1)
                        {
                            string ret = AuditCorpReg(strGuid, "5", flowcode, "主管用户CA申请审核");
                            OperationResult result = JsonConvert.DeserializeObject<OperationResult>(ret);
                            if (result.Result == true)
                            {
                                ListCorps.Rebind();
                                ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('" + result.Message + "');", true);
                            }
                            else
                            {
                                ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('" + result.Message + "');", true);
                            }
                        }

                    }
                    catch (Exception ex)
                    {
                        hidSysError.Value = ex.Message;
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('数据加载失败！');", true);
                    }
                    break;

                #endregion

                #region Back
                case "Back":
                    try
                    {
                        int checkCount = 0;
                        string flowcode = string.Empty;
                        string strGuid = string.Empty;
                        foreach (GridDataItem dataItem in ListCorps.MasterTableView.Items)
                        {
                            if ((dataItem.FindControl("CheckBox1") as CheckBox).Checked == true)
                            {
                                strGuid = dataItem.GetDataKeyValue("CorpUserGuid").ToString();
                                flowcode = dataItem["FlowCode"].Text;
                                checkCount++;
                                if (checkCount >= 2)
                                {
                                    //只能选择一条数据
                                    ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('只能选择一条数据！');", true);
                                    return;
                                }
                            }
                        }
                        if (checkCount == 0)
                        {
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('请选择要退回的数据！');", true);
                        }
                        else if (checkCount == 1)
                        {
                            string ret = AuditCorpReg(strGuid, "6", flowcode, "主管用户CA申请退回");
                            OperationResult result = JsonConvert.DeserializeObject<OperationResult>(ret);
                            if (result.Result == true)
                            {
                                ListCorps.Rebind();
                                ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('" + result.Message + "');", true);
                            }
                            else
                            {
                                ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('" + result.Message + "');", true);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        hidSysError.Value = ex.Message;
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('数据加载失败！');", true);
                    }
                    break;

                #endregion

                #region Default
                default:
                    break;
                #endregion
            }
        }

        /// <summary>
        /// 只显示N个字的方法
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public string StrCut(string str, int num)
        {
            string nstr = System.Text.RegularExpressions.Regex.Replace(str, @"<[^>]*>", "");
            nstr = nstr.Replace("&nbsp;<STRONG></STRONG>", "");
            if (nstr.Length >= num)
            {
                return nstr.Substring(0, num) + "...";
            }
            return nstr;
        }

        public override bool IsCheckPermission
        {
            get { return false; }
        }
    }
}